import BaseNode, {NodeType} from './BaseNode'
import CommonNode from './CommonNode'
import DecisionNode from './DecisionNode'
import { v4 as uuidv4 } from 'uuid'
import StartNode from './StartNode'
import OptionNode from './OptionNode'

export default class Chapter extends BaseNode {

  type:string = 'chapter'

  nodes:Record<string, BaseNode> = {}

  property:Record<string, any> = {}

  addNode=(t:NodeType, uuid:string = uuidv4(), prev?: string) => {
    if (t === 'start') {
      const startNode = new StartNode(uuid)
      startNode.prev = prev ?? ''
      this.nodes[uuid] = startNode
    }

    if (t === 'common') {
      const commonNode = new CommonNode(uuid)
      commonNode.prev = prev ?? ''
      this.nodes[uuid] = commonNode
    }

    if (t === 'decision') {
      const decisionNode = new DecisionNode(uuid)
      decisionNode.prev = prev ?? ''
      this.nodes[uuid] = decisionNode
    }
  }

 
  toObj:Function=(file:Record<string, any>) => {
    const keys = Object.keys(file)
    for(let key of keys){
      if((this as any)[key]){
        ;(this as any)[key] = file[key]
      }
    }
    if(file?.nodes){
      for(let key in file.nodes){
        if(file?.nodes[key].type==='start'){
          const start = new StartNode(file?.nodes[key].uuid)
          start.toObj(file?.nodes[key])
          ;(this as any).nodes[key] = start
        }
        if(file?.nodes[key].type==='common'){
          const common = new CommonNode(file?.nodes[key].uuid)
          common.toObj(file?.nodes[key])
          ;(this as any).nodes[key] = common
        }
        if(file?.nodes[key].type==='decision'){
          const decision = new DecisionNode(file?.nodes[key].uuid)
          decision.toObj(file?.nodes[key])
          ;(this as any).nodes[key] = decision
        }
        if(file?.nodes[key].type==='option'){
          const option = new OptionNode(file?.nodes[key].uuid)
          option.toObj(file?.nodes[key])
          ;(this as any).nodes[key] = option
        }
      }
    }
    return this
  }
  
}
